from openpyxl import load_workbook
import os

import configparser
import sys


config = configparser.ConfigParser()

config["PIXL"] = {
    "table": "A15_properties_07082024.xlsx",
    "sheet": "Sheet1",
    "skuid": 2,
    "start_col": "D",
    "end_col": "G",
}

def gen_properties_file(product):
    workbook = load_workbook(filename=config[product]["table"], data_only=True)
    sheet = workbook[config[product]["sheet"]]
    properties_names = [cell.value.strip() if cell.value else cell.value for cell in sheet["A"]]
    skip_list = [
        None,
        "Properties name",
        "ro.boot.skuid",
        "VARIANT BUILD",
        "ro.carrier",
        "ro.build.id",
        "ro.build.tags",
    ]

    dynamic_props = [
        "ro.build.fingerprint",
        "ro.system.build.fingerprint",
        "ro.system_ext.build.fingerprint",
        "ro.odm.build.fingerprint",
        "ro.vendor.build.fingerprint",
        "ro.bootimage.build.fingerprint",
        "ro.product.build.fingerprint",
        "ro.build.display.id",
        "ro.build.software.version",
        "ro.build.version.incremental",
        "ro.product.model.display",
        "ro.product.model",
        "ro.product.nickname",
    ]

    skip_list.extend(dynamic_props)

    skuid_row = 0
    product_name_row = 0
    for i, prop in enumerate(properties_names):
        if prop == "ro.boot.skuid":
            skuid_row = i
        elif prop == "ro.product.name":
            product_name_row = i

    for col in range(
        ord(config[product]["start_col"]), ord(config[product]["end_col"]) + 1
    ):
        column_values = [cell.value for cell in sheet[chr(col)]]

        skuid = column_values[skuid_row]
        product_name = column_values[product_name_row]

        prop_dir = os.path.join(os.getcwd(), product, skuid)
        if not os.path.exists(prop_dir):
            os.makedirs(prop_dir)

        prop_file = os.path.join(prop_dir, f"{product_name}.prop")
        print(prop_file)
        with open(prop_file, "w", encoding="utf-8") as f:
            for i, prop in enumerate(properties_names):
                if prop not in skip_list:
                    val = column_values[i]
                    if isinstance(val, str):
                        val = val.replace("<Do not set>", "")
                        val = val.replace("<Do Not Set>", "")
                        val = val.replace("None", "")
                    print(f"{i}: {prop}={val}")
                    f.write(f"{prop}={val}\n")
        f.close()


if __name__ == "__main__":
    if len(sys.argv) > 1:
        print("传入的参数:")
        for arg in sys.argv[1:]:
            print(arg)
            if config.has_section(arg):
                gen_properties_file(arg)
    else:
        print("没有传入参数")
